package top.maof.mfcoin.net;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;

@Slf4j
public class NioServer {
    // 本地服务器监听的端口
    private static final int Listening_Port = 8888;

    // 缓冲区大小
    private static final int Buffer_Size = 1024;


    public static void main(String[] args) throws IOException {
        // 创建一个在本地端口进行监听的服务Socket信道.并设置为非阻塞方式
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.socket().bind(new InetSocketAddress(Listening_Port));
        serverChannel.configureBlocking(false);
        // 创建一个选择器并将serverChannel注册到它上面
        Selector selector = Selector.open();
        //设置为客户端请求连接时，默认客户端已经连接上
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        Worker worker = new Worker();

        while (true) {
            // 轮询监听key，select是阻塞的，accept()也是阻塞的
            selector.select();
            // 有客户端请求，被轮询监听到
            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {
                SelectionKey key = keyIter.next();
                if (key.isAcceptable()) {
                    log.info("接收");
                    SocketChannel clientChannel = ((ServerSocketChannel) key.channel()).accept();
                    worker.register(clientChannel);
                    worker.start();
                }
                keyIter.remove();
            }
        }
    }


    @Data
    @Slf4j
    static class Worker implements Runnable {
        Selector selector;

        Thread thread;

        volatile int num = 0;

        boolean isStart = false;

        ConcurrentLinkedQueue<Runnable> concurrentLinkedQueue = new ConcurrentLinkedQueue();

        public Worker() {
            try {
                selector = Selector.open();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        public void register(SocketChannel clientChannel) {
            selector.wakeup();

            concurrentLinkedQueue.add(new Runnable() {
                @Override
                public void run() {
                    try {
                        clientChannel.configureBlocking(false);
                        clientChannel.register(selector, SelectionKey.OP_READ);
                        num++;
                        log.info("第{}个用户", num);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

        }

        public void start() {
            if (!isStart) {
                isStart = true;
                thread = new Thread(this);
                thread.start();
            }
        }


        @Override
        public void run() {
            while (true) {
                // 轮询监听key，select是阻塞的，accept()也是阻塞的
                try {
                    selector.select();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Runnable runnable = concurrentLinkedQueue.poll();
                if (runnable != null)
                    runnable.run();
                // 有客户端请求，被轮询监听到
                Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
                while (keyIter.hasNext()) {
                    SelectionKey key = keyIter.next();
                    if (key.isReadable()) {
                        log.info("可读");
                        key.cancel();
                    }
                    keyIter.remove();
                }
            }

        }
    }
}
